<template>
  <div>
    <div class="app-container">
      <el-container>
        <el-header>
          <el-form ref="queryFormRef" :model="queryForm" :inline="true">
            <!-- StartDate  EndDate -->
            <el-form-item prop="keywords">
              <el-input v-model="queryForm.keywords" placeholder="请输入关键字" clearable style="width: 200px" />
              <el-button type="primary" style="margin-left: 0; border-radius: 0" @click="handleQuery"> 搜索 </el-button>
            </el-form-item>
            <el-form-item>
              <el-button v-if="permissions.create" type="success" @click="openDialog()"
                ><i-ep-plus />新增班组</el-button
              >
              <el-button v-if="permissions.createWorker" type="success" @click="handleCreate"
                ><i-ep-plus />入场登记</el-button
              >
            </el-form-item>
          </el-form>
        </el-header>
        <el-container v-loading="loading">
          <el-aside width="300px">
            <el-tree-v2
              ref="allTreeRef"
              :data="allCorpGroupTree"
              :props="defaultProps"
              :highlight-current="true"
              :indent="20"
              :item-size="40"
              :expand-on-click-node="false"
              :height="600"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <div style="width: 100%">
                  <div v-if="data.extend1 == 'Corp'" style="float: left">
                    <OfficeBuilding style="width: 20px" /> {{ node.label }}({{ data.extend2 }})
                  </div>
                  <div v-if="data.extend1 == 'Group'" style="float: left">
                    <Flag style="width: 20px" /> {{ node.label }}({{ data.extend3 }})
                  </div>
                </div>
              </template>
            </el-tree-v2>
          </el-aside>
          <el-main>
            <div style="margin-bottom: 20px">
              <el-button v-if="permissions.allin" :disabled="ids.length == 0" type="primary" @click="getInOrOut('in')"
                >一键进场</el-button
              >
              <el-button v-if="permissions.allout" :disabled="ids.length == 0" type="primary" @click="getInOrOut('out')"
                >一键离场</el-button
              >
              <el-button v-if="permissions.export" type="primary" :loading="download_loading" @click="download()"
                ><i-ep-download />导出</el-button
              >
            </div>
            <el-table
              ref="tableRef"
              :data="tableData"
              row-key="groupId"
              style="width: 100%"
              @expand-change="loadTable"
              @selection-change="handleSelectionChange"
            >
              <el-table-column v-if="userType === 'Manager'" type="selection" width="30" align="center" />
              <el-table-column type="expand" width="20">
                <template #default="props">
                  <div style="margin-left: 50px">
                    <el-table
                      v-loading="dicExpand[props.row.groupId].loading"
                      :data="dicExpand[props.row.groupId].data"
                      row-key="id"
                      style="width: 100%; display: flex; margin: auto"
                      align="center"
                    >
                      <el-table-column label="工人姓名" prop="personName" min-width="80" />
                      <el-table-column label="证件号码" prop="cardNumber" min-width="160" />
                      <el-table-column label="人员状态">
                        <template #default="scope">
                          <el-tag :type="scope.row.status ? 'success' : 'danger'">{{
                            scope.row.status ? "在场" : "离场"
                          }}</el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column label="班组长" min-width="70">
                        <template #default="scope">
                          <el-tag v-if="scope.row.isLeader === true" type="success">是</el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column label="劳动合同">
                        <template #default="scope">
                          <el-tag :type="scope.row.hasContract ? 'success' : 'danger'">{{
                            scope.row.hasContract ? "已签订" : "未签订"
                          }}</el-tag>
                        </template>
                      </el-table-column>
                      <el-table-column
                        label="工种/岗位类型"
                        prop="typeName"
                        min-width="105"
                        :formatter="(row) => (row.isManager == true ? row.postCategoryName : row.typeName)"
                      />
                      <el-table-column label="联系电话" prop="mobile" min-width="105" />
                      <el-table-column label="进场日期" prop="startDate" min-width="95" />
                      <el-table-column label="离场日期" prop="endDate" min-width="95" />
                      <el-table-column fixed="right" label="操作" align="center" min-width="150">
                        <template #default="scope">
                          <el-button
                            v-if="permissions.editWorker"
                            type="primary"
                            link
                            @click.stop="handleEdit(scope.row)"
                            >编辑</el-button
                          >
                          <el-button type="primary" link @click.stop="handleDetail(scope.row)">详情</el-button>
                          <el-button
                            v-if="permissions.changeGroup && scope.row.status === 1 && scope.row.isManager != true"
                            type="primary"
                            link
                            @click="openDialogGroup(scope.row)"
                            ><i-ep-edit />更换班组</el-button
                          >
                          <el-button
                            v-if="permissions.out && scope.row.status === 1"
                            type="primary"
                            link
                            @click.stop="updateMemberStatus(scope.row.id, 'out')"
                            >离场</el-button
                          >
                          <el-button
                            v-if="permissions.in && scope.row.status != 1"
                            type="primary"
                            link
                            @click.stop="updateMemberStatus(scope.row.id, 'in')"
                            >进场</el-button
                          >
                          <el-button
                            v-if="permissions.setLeader && scope.row.isManager != true"
                            type="primary"
                            link
                            @click.stop="editMemberLeader(scope.row.id)"
                            >设为组长</el-button
                          >
                          <el-button
                            v-if="permissions.setLeader"
                            type="primary"
                            link
                            @click.stop="sendDevice(scope.row.id, 1)"
                            >下发进场</el-button
                          >
                          <el-button
                            v-if="permissions.setLeader"
                            type="primary"
                            link
                            @click.stop="sendDevice(scope.row.id, 0)"
                            >下发离场</el-button
                          >
                          <el-button type="primary" link @click.stop="handleVerifyImage(scope.row)">现场核验</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <pagination
                      v-if="dicExpand[props.row.groupId].total > 0"
                      v-model:total="dicExpand[props.row.groupId].total"
                      v-model:page="dicExpand[props.row.groupId].query.pageNum"
                      v-model:limit="dicExpand[props.row.groupId].query.pageSize"
                      small
                      @pagination="loadTable(props.row)"
                    />
                  </div>
                </template>
              </el-table-column>
              <el-table-column v-if="userType != 'Manager'" label="项目名称" prop="projectName" />
              <el-table-column label="参建单位" prop="corpName" />
              <el-table-column label="班组名称" prop="name" />
              <el-table-column label="管理部班组">
                <template #default="scope">
                  <el-tag v-if="scope.row.isManagerGroup === true" type="success">是</el-tag>
                  <el-tag v-if="scope.row.isManagerGroup === false" type="danger">否</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="进场日期" prop="startDate" />
              <el-table-column label="退场日期" prop="endDate" />
              <el-table-column label="班组长" prop="groupMemberLeader" />
              <el-table-column label="班组长联系电话" prop="groupMemberLeaderMobile" />
              <el-table-column
                v-if="userType === 'Manager' || userType === 'Corp'"
                fixed="right"
                label="操作"
                align="center"
              >
                <template #default="scope">
                  <el-button v-if="permissions.update" type="primary" link @click="openDialog(scope.row.groupId)"
                    ><i-ep-edit />编辑</el-button
                  >
                  <el-button v-if="permissions.delete" type="primary" link @click.stop="handleDelete(scope.row.groupId)"
                    ><i-ep-delete />删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-main>
        </el-container>
      </el-container>
      <add-form
        v-if="dialogAddOrEdit.visible"
        :dialog-add-or-edit="dialogAddOrEdit"
        :group-id="queryForm.groupId"
        :group-name="queryForm.groupName"
        :is-manager="isManager"
        :corp-role="corpRole"
        @send-close="sendClose"
      />
      <add-contract
        v-if="dialogAddContract.visible"
        :dialog-add-contract="dialogAddContract"
        :worker-info="curWorkerInfo"
        @send-close="contractSendClose"
      />
      <detail v-if="dialogDetail.visible" :dialog-detail="dialogDetail" @send-close="sendClose" />
    </div>
    <!--编辑弹窗-->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500" class="system" draggable @close="closeDialog">
      <el-form ref="groupFormRef" :model="formData" :rules="rules" label-width="120px" style="padding-right: 70px">
        <el-form-item label="班组名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入班组名称" />
        </el-form-item>
        <el-form-item label="参建企业" prop="corpId">
          <el-input v-model="formData.corpName" readonly placeholder="请选择参建企业" class="input300 inputred">
          </el-input>
          <el-button type="primary" style="position: absolute; right: -80px" plain @click="openCorpSelect">
            <el-icon> <OfficeBuilding /> </el-icon>&nbsp;选择
          </el-button>
        </el-form-item>
        <el-form-item label="进场日期" prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择进场日期"
            style="width: 100%"
            @change="formData.endDate = undefined"
          />
        </el-form-item>
        <el-form-item label="离场日期" prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled="!formData.startDate"
            type="date"
            placeholder="请选择离场日期"
            style="width: 100%"
            :disabled-date="disabledEndDate"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--更换人员班组-->
    <el-dialog
      v-model="dialogMember.visible"
      :title="dialogMember.title"
      width="500"
      class="system"
      close-icon="CloseBold"
      draggable
      @close="closeDialog"
    >
      <el-form ref="groupMemberFormRef" :model="memberformData" :rules="rulesMember" label-width="100px">
        <el-form-item label="原班组名称" prop="name">
          <el-input v-model="memberformData.name" readonly />
        </el-form-item>
        <el-form-item label="变更班组" prop="newGroupId">
          <el-select v-model="memberformData.newGroupId" style="width: 100%">
            <el-option
              v-for="item in projectGroupsPullDown"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="进场日期" prop="startDate">
          <el-date-picker
            v-model="memberformData.startDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择进场日期"
            style="width: 100%"
            @change="memberformData.endDate = undefined"
          />
        </el-form-item>
        <el-form-item label="离场日期" prop="endDate">
          <el-date-picker
            v-model="memberformData.endDate"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled="!memberformData.startDate"
            type="date"
            placeholder="请选择离场日期"
            style="width: 100%"
            :disabled-date="disabledMemberEndDate"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitMember">确 定</el-button>
          <el-button @click="closeDialogMember">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--选择企业-->
    <SelectCorp
      v-if="dialogSelectCorp.visible"
      :dialog-select-corp="dialogSelectCorp"
      :corp-list-query="'team'"
      @corp-send-close="corpSendClose"
    ></SelectCorp>
    <verifyImage v-if="dialogVerifyImage.visible" :dialog-verify-image="dialogVerifyImage" @send-close="sendClose">
    </verifyImage>
  </div>
</template>
<script lang="ts" setup>
/**引入文件**/
import addForm from "@/views/commonpage/worker/workerinfo/addForm.vue";
import addContract from "@/views/commonpage/worker/workerinfo/addContract.vue";
import detail from "@/views/commonpage/worker/workerinfo/detail.vue";
import verifyImage from "./components/verifyImage.vue";
import { downloadFile } from "@/utils";
import { Tree, projectGroupListVo, projectGroupForm, UpdatePersonMemberformData } from "@/api/worker/types";
import {
  getProjectGroupMembers,
  QueryProjectGroupMembers,
  deleteGroups,
  getGroupForm,
  updateGroup,
  addGroup,
  inGroups,
  outGroups,
  pullDownGroups,
  updatePersonMember,
  inGroupMember,
  outGroupMember,
  downloadGroups,
  EditMemberLeader,
  SendDevice,
  GetCorpGroupByName,
} from "@/api/worker/index";
import SelectCorp from "@/views/manager/common/SelectCorp/index.vue";
import type Node from "element-plus/es/components/tree/src/model/node";
import { ElMessageBox, ElDatePicker, ElForm, ElFormItem } from "element-plus";
import moment from "moment";

/**权限处理 */
const currentSystem = ref(localStorage.getItem("usertypeName"));
const isLumpContractor = ref(localStorage.getItem("isLumpContractor")); //是否是总包
const permissions = ref({
  create: false,
  update: false,
  detail: true,
  export: false,
  allin: false,
  allout: false,
  in: false,
  out: false,
  changeGroup: false,
  setLeader: false,
  delete: false,
  createWorker: false,
  editWorker: false,
});

if (currentSystem.value == "Manager") {
  permissions.value = {
    create: true,
    update: true,
    detail: true,
    export: true,
    allin: true,
    allout: true,
    in: true,
    out: true,
    changeGroup: true,
    setLeader: true,
    delete: false,
    createWorker: true,
    editWorker: true,
  };
}
if (currentSystem.value == "Corp") {
  permissions.value = {
    create: true,
    update: true,
    detail: true,
    export: true,
    allin: false,
    allout: false,
    in: true,
    out: true,
    changeGroup: true,
    setLeader: true,
    delete: false,
    createWorker: true,
    editWorker: true,
  };
}

const dialogAddOrEdit = reactive({
  visible: false,
});
const dialogAddContract = reactive<DialogOption>({
  visible: false,
});
const dialogDetail = reactive<DialogOption>({
  visible: false,
});
const dialogVerifyImage = reactive<DialogOption>({
  visible: false,
});
const curWorkerInfo = ref();

//结束时间禁用范围
const disabledEndDate = (time: Date) => {
  if (formData.startDate) {
    return time.getTime() <= new Date(formData.startDate).getTime();
  }
};
const disabledMemberEndDate = (time: Date) => {
  if (memberformData.startDate) {
    return time.getTime() <= new Date(memberformData.startDate).getTime();
  }
};
//新增
const handleCreate = () => {
  if (queryForm.groupId == "") {
    return ElMessage.error("请选择班组");
  }
  dialogAddOrEdit.visible = true;
  dialogAddOrEdit.footBtn = "确认新增";
  dialogAddOrEdit.title = "新增";
  dialogAddOrEdit.type = 1;
};
//编辑
const handleEdit = (row: any) => {
  console.log(row);
  isManager.value = tableData.value.find((item: any) => item.groupId == row.groupId).isManagerGroup;
  dialogAddOrEdit.visible = true;
  dialogAddOrEdit.id = row.id;
  dialogAddOrEdit.footBtn = "确认修改";
  dialogAddOrEdit.title = "修改";
  dialogAddOrEdit.type = 2;

  //  :group-id="queryForm.groupId"
  //     :group-name="queryForm.groupName"
  //     :is-manager="isManager"
  //     :corp-role="corpRole"
};

//详情
const handleDetail = (row: any) => {
  dialogDetail.visible = true;
  dialogDetail.id = row.id;
  dialogDetail.title = "详情";
};

const handleVerifyImage = (row: any) => {
  dialogVerifyImage.visible = true;
  dialogVerifyImage.title = "现场核验";
  dialogVerifyImage.id = row.cardNumber;
  dialogVerifyImage.personId = row.personId;
};

const contractSendClose = (needRefresh: boolean) => {
  dialogAddContract.visible = false;
  if (needRefresh) {
    handleQuery();
  }
};

const sendClose = (needRefresh: boolean, workerInfo?: any) => {
  dialogAddOrEdit.visible = false;
  dialogAddOrEdit.id = undefined;
  dialogDetail.visible = false;
  dialogDetail.id = undefined;
  isManager.value = false;
  dialogVerifyImage.visible = false;
  dialogVerifyImage.id = undefined;
  if (needRefresh) {
    handleQuery();
  }
  if (workerInfo) {
    dialogAddContract.visible = true;
    dialogAddContract.title = "添加合同";
    dialogAddContract.footBtn = "确认添加";
    curWorkerInfo.value = workerInfo;
  }
};

const allCorpGroupTree = ref<any[]>([]);
const defaultProps = {
  leaf: "leaf",
  value: "id",
  label: "label",
  children: "children",
};
const allTreeRef = ref();
const isManager = ref(false);
const corpRole = ref("");
//树节点点击事件
const handleNodeClick = (data: any) => {
  console.log(data);
  if (data.extend1 == "Group") {
    queryForm.groupId = data.id;
    queryForm.groupName = data.label;
    console.log(queryForm.groupName);
    isManager.value = data.extend2;
    tableData.value = oldTableData.value.filter((i: any) => i.groupId == data.id);
    corpRole.value = allCorpGroupTree.value.find(
      (i: any) => i.children.findIndex((j) => j.id == data.id) > -1
    )?.extend2;
  }
  if (data.extend1 == "Corp") {
    queryForm.groupId = "";
    queryForm.corpId = data.id;
    tableData.value = oldTableData.value.filter((i: any) => i.corpId == data.id);
  }
};

// const loading = ref(false);
//这是列表数据
const tableData = ref<any[]>([]);
const oldTableData = ref();

const dicMap = ref(new Map());
const loadings = ref(new Map());
const tableDataLoading = ref(false);
const loading = ref(false);
const ids = ref<number[]>([]);
const userType = localStorage.getItem("usertypeName");
const groupFormRef = ref();
const groupMemberFormRef = ref();
const projectGroupsPullDown = ref([] as any[]);
const download_loading = ref(false);
const dialog = reactive<DialogOption>({
  visible: false,
});
const dialogMember = reactive<DialogOption>({
  visible: false,
});
const formData = reactive<projectGroupForm>({});
const memberformData = reactive<UpdatePersonMemberformData>({});

const dialogSelectCorp = reactive({
  visible: false,
  title: "选择企业",
  id: 0,
  corpId: 0,
});
const tableRef = ref();

const queryForm = reactive({
  pageIndex: 1,
  pageSize: 10,
  keywords: "",
  groupId: "",
  corpId: "",
} as any);

const handleQuery = () => {
  loading.value = true;
  tableData.value.forEach((row: any) => {
    tableRef.value.toggleRowExpansion(row, false);
  });
  GetCorpGroupByName(queryForm.keywords)
    .then((res) => {
      if (res.success) {
        allTreeRef.value.setExpandedKeys(res.data.corpGroupTree.map((item: any) => item.id));
        allCorpGroupTree.value = res.data.corpGroupTree;
        tableData.value = res.data.projectGroupDto;
        oldTableData.value = res.data.projectGroupDto;
      } else {
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

//生命周期事件
onMounted(async () => {
  handleQuery();
});

function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.groupId);
}

const dicExpand = ref<any>({});

//加载成员信息
const loadTable = function (row: projectGroupListVo, expandRows: any) {
  if (dicExpand.value.hasOwnProperty(row.groupId)) {
    dicExpand.value[row.groupId].loading = true;
  } else {
    dicExpand.value[row.groupId] = {
      query: {
        pageNum: 1,
        pageSize: 10,
        groupId: row.groupId,
      },
      total: 0,
      loading: true,
      data: [],
    };
  }
  QueryProjectGroupMembers(dicExpand.value[row.groupId].query).then((res) => {
    if (res.success === true) {
      //dicMap.value.set(row.groupId, res.data);
      dicExpand.value[row.groupId].data = res.data.list;
      dicExpand.value[row.groupId].loading = false;
      dicExpand.value[row.groupId].total = res.data.total;
      dicExpand.value[row.groupId].pageNum = res.data.pageNum;
      dicExpand.value[row.groupId].pageSize = res.data.pageSize;
    }
    loadings.value.set(row.groupId, false);
  });
};

function sendDevice(id?: number, type?: number) {
  var msg = "确认将该人员下发到设备？";
  if (type == 1) msg = "确认将该人员下发到设备？";
  else msg = "确认将该人员从设备删除？";
  ElMessageBox.confirm(msg, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      tableDataLoading.value = true;
      SendDevice(id, type)
        .then((resp) => {
          if (resp.success === true) {
            ElMessage.success(resp.msg);
            handleQuery();
          } else {
            ElMessage.warning(resp.msg);
          }
        })
        .finally(() => (tableDataLoading.value = false));
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消！",
      });
    });
}
//更换班组长
function editMemberLeader(id?: number) {
  if (!id) return ElMessage.warning("请选择要更换的班组长");
  ElMessageBox.confirm("确认更换班组长?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      tableDataLoading.value = true;
      EditMemberLeader(id)
        .then((resp) => {
          if (resp.success === true) {
            ElMessage.success(resp.msg);
            handleQuery();
          } else {
            ElMessage.warning(resp.msg);
          }
        })
        .finally(() => (tableDataLoading.value = false));
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消！",
      });
    });
}

//删除
function handleDelete(id?: number) {
  const groupids = [id || ids.value].join(",");
  if (!groupids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      tableDataLoading.value = true;
      deleteGroups(groupids)
        .then((resp) => {
          if (resp.success === true) {
            ElMessage.success(resp.msg);
            handleQuery();
          } else {
            ElMessage.warning(resp.msg);
          }
        })
        .finally(() => (tableDataLoading.value = false));
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消！",
      });
    });
}

//更换人员班组弹窗
function openDialogGroup(row?: any) {
  dialogMember.visible = true;
  dialogMember.title = "更换【" + row.personName + "】班组";
  memberformData.name = row.groupName;
  memberformData.oldGroupId = row.groupId;
  memberformData.personId = row.personId;
  pullDownGroups(row.corpId).then((res) => {
    if (res.success === true) {
      projectGroupsPullDown.value = res.data.filter((item: any) => item.extend1 !== true);
    }
  });
}

//编辑弹窗
function openDialog(id?: number) {
  dialog.visible = true;
  dialog.title = "编辑班组";
  if (id) {
    getGroupForm(id).then((res) => {
      Object.assign(formData, res.data);
    });
  } else {
    dialog.title = "新增班组";
    resetForm();
  }
}

/**
 * 重置表单
 */
function resetForm() {
  groupFormRef.value.resetFields();
  groupFormRef.value.clearValidate();
  formData.corpId = undefined;
  formData.corpName = "";
  formData.groupId = undefined;
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
}
function closeDialogMember() {
  dialogMember.visible = false;
}

/* 打开企业选择 */
function openCorpSelect() {
  dialogSelectCorp.visible = true;
}
function corpSendClose(data: any) {
  if (data) {
    formData.corpId = data.corpId;
    formData.corpName = data.name;
  }
  dialogSelectCorp.visible = false;
}
const outFormData = ref<any>({
  id: 0,
  endDate: "",
});
const outRules = {
  endDate: [
    {
      required: true,
      message: "请选择离场时间",
      trigger: "change",
    },
  ],
};
const outFormValidate = ref<boolean>(false);

//单个人员进出场
function updateMemberStatus(id: number, type: string) {
  if (type === "in") {
    ElMessageBox.confirm("确认进场?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        tableDataLoading.value = true;
        inGroupMember(id)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              tableData.value.forEach((row: any) => {
                tableRef.value.toggleRowExpansion(row, false);
              });
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (tableDataLoading.value = false));
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消！",
        });
      });
  } else if (type === "out") {
    ElMessageBox({
      title: "确认离场?",
      message: () =>
        h("div", [
          h(
            ElForm,
            {
              ref: "outFormRef",
              model: outFormData,
              rules: outRules,
              inline: true,
              labelWidth: "100px",
              onValidate(prop, isValid, message) {
                if (prop == "endDate") {
                  outFormValidate.value = isValid;
                }
              },
            },
            [
              h(
                ElFormItem,
                {
                  prop: "endDate",
                  label: "离场时间",
                },
                [
                  h(ElDatePicker, {
                    modelValue: outFormData.value.endDate,
                    type: "date",
                    "onUpdate:modelValue": (val: any) => {
                      outFormData.value.endDate = moment(val).format("YYYY-MM-DD");
                    },
                  }),
                ]
              ),
            ]
          ),
        ]),
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      showCancelButton: true,
      beforeClose(action, instance, done) {
        if (action === "confirm") {
          if (!outFormValidate.value) return ElMessage.warning("请填写离场时间");
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "执行中...";
          outGroupMember(id, outFormData.value.endDate)
            .then((res) => {
              if (res.success === true) {
                outFormData.value.endDate = "";
                outFormValidate.value = false;
                ElMessage.success(res.msg);
                handleQuery();
                done();
              } else {
                ElMessage.warning(res.msg);
              }
            })
            .finally(() => {
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "确定";
            });
        } else {
          done();
        }
      },
    });
  }
}

//一键进出场
function getInOrOut(type: string, id?: number) {
  if (ids.value.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return false;
  }
  const groupids = [id || ids.value].join(",");
  if (type === "in") {
    ElMessageBox.confirm("确认一键进场已选中的班组项?", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        tableDataLoading.value = true;
        inGroups(groupids)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              tableData.value.forEach((row: any) => {
                tableRef.value.toggleRowExpansion(row, false);
                tableRef.value.toggleRowSelection(row, false);
              });
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (tableDataLoading.value = false));
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消！",
        });
      });
  } else if (type === "out") {
    ElMessageBox({
      title: "确认一键离场已选中的班组项?",
      message: () =>
        h("div", [
          h(
            ElForm,
            {
              ref: "outFormRef",
              model: outFormData,
              rules: outRules,
              inline: true,
              labelWidth: "100px",
              onValidate(prop, isValid, message) {
                if (prop == "endDate") {
                  outFormValidate.value = isValid;
                }
              },
            },
            [
              h(
                ElFormItem,
                {
                  prop: "endDate",
                  label: "离场时间",
                },
                [
                  h(ElDatePicker, {
                    modelValue: outFormData.value.endDate,
                    type: "date",
                    "onUpdate:modelValue": (val: any) => {
                      outFormData.value.endDate = moment(val).format("YYYY-MM-DD");
                    },
                  }),
                ]
              ),
            ]
          ),
        ]),
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      showCancelButton: true,
      beforeClose(action, instance, done) {
        if (action === "confirm") {
          if (!outFormValidate.value) return ElMessage.warning("请填写离场时间");
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "执行中...";
          outGroups(groupids, outFormData.value.endDate)
            .then((res) => {
              if (res.success === true) {
                outFormData.value.endDate = "";
                outFormValidate.value = false;
                ElMessage.success(res.msg);
                handleQuery();
                done();
              } else {
                ElMessage.warning(res.msg);
              }
            })
            .finally(() => {
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "确定";
            });
        } else {
          done();
        }
      },
    });
  }
}

//验证
const rules = reactive({
  name: [{ required: true, message: "请输入班组名称", trigger: "blur" }],
  corpId: [{ required: true, message: "请选择参建单位", trigger: "blur" }],
  startDate: [{ required: true, message: "请选择进场日期", trigger: "blur" }],
  endDate: [{ required: true, message: "请选择离场日期", trigger: "blur" }],
});
const rulesMember = reactive({
  newGroupId: [{ required: true, message: "请选择更换班组", trigger: "blur" }],
  startDate: [{ required: true, message: "请选择进场日期", trigger: "blur" }],
  endDate: [{ required: true, message: "请选择离场日期", trigger: "blur" }],
});

//更换人员所在班组提交
function handleSubmitMember() {
  groupMemberFormRef.value.validate((valid: any) => {
    if (valid) {
      tableDataLoading.value = true;
      updatePersonMember(memberformData)
        .then((resp) => {
          if (resp.success === true) {
            ElMessage.success(resp.msg);
            closeDialogMember();
            tableData.value.forEach((row: any) => {
              tableRef.value.toggleRowExpansion(row, false);
            });
          } else {
            ElMessage.warning(resp.msg);
          }
        })
        .finally(() => (tableDataLoading.value = false));
    }
  });
}

function download() {
  download_loading.value = true;
  downloadGroups().then((response: any) => {
    if (!response.headers["content-disposition"]) {
      const decoder = new TextDecoder("utf-8");
      const resp = decoder.decode(response.data);
      let objResp = JSON.parse(resp);
      ElMessage.error(objResp.msg);
      download_loading.value = false;
      return;
    }

    downloadFile(response);
    download_loading.value = false;
  });
}

/**
 * 新增编辑表单提交
 */
function handleSubmit() {
  groupFormRef.value.validate((valid: any) => {
    if (valid) {
      tableDataLoading.value = true;
      const groupId = formData.groupId;
      formData.isManagerGroup = false;
      if (groupId) {
        updateGroup(groupId, formData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog();
              handleQuery();
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (tableDataLoading.value = false));
      } else {
        addGroup(formData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog();
              handleQuery();
            } else {
              ElMessage.warning(resp.msg);
            }
          })
          .finally(() => (tableDataLoading.value = false));
      }
    }
  });
}
</script>
<style lang="scss" scoped>
:deep(.el-aside) {
  padding: 20px;
  background-color: #ffffff;
  margin-right: 20px;
}

:deep(.el-header) {
  padding: 20px;
  background-color: #ffffff;
  margin-bottom: 20px;
}

:deep(.el-main) {
  padding: 20px;
  background-color: #ffffff;
  min-height: 680px;
}

.el-menu {
  border-right: 0 !important;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background-color: #3b98f7 !important;
  color: #fff;
  fill: #fff !important;
}

:deep(.el-tree-node__content) {
  color: #000;
}

.icon {
  margin-right: 10px;
}
</style>
